package nix.bs.service;

import nix.bs.dao.UserDao;
import nix.bs.domain.User;

public class UserService {

	private UserDao userDao = new UserDao();

	/**
	 * 注册
	 */
	public void regist(User form) throws UserException {
		if (userDao.findByUsername(form.getUsername()) != null) {
			throw new UserException("用户名已存在！");
		}
		if (userDao.findByEmail(form.getEmail()) != null) {
			throw new UserException("Email已存在！");
		}
		userDao.add(form);
	}

	/**
	 * 激活
	 */
	public void active(String code) throws UserException {
		User user = userDao.findByCode(code);
		if (user == null) {
			throw new UserException("激活码无效！");
		}
		if (user.isState()) {
			throw new UserException("您已经激活过了！");
		}
		userDao.updateState(user.getUid(), true);
	}

	/**
	 * 登陆
	 */
	public User login(User form) throws UserException {
		User user = userDao.findByUsername(form.getUsername());
		if (user == null) {
			throw new UserException("用户不存在！");
		}
		if (!user.getPassword().equals(form.getPassword())) {
			throw new UserException("密码不正确！");
		}
		if (!user.isState()) {
			throw new UserException("您的账号未激活！");
		}
		return user;
	}
}
